package com.aeoj.clientmanagement.service.impl;

import com.aeoj.clientmanagement.domain.problem.dto.ProblemSubmitDTO;
import com.aeoj.clientmanagement.domain.problemrecord.ProblemRecord;
import com.aeoj.clientmanagement.domain.user.vo.SysUserVO;
import com.aeoj.clientmanagement.enums.ResponseCodeEnum;
import com.aeoj.clientmanagement.enums.problem.ProblemRrecordStatusEnum;
import com.aeoj.clientmanagement.enums.problem.ProblemSubmitLanguageEnum;
import com.aeoj.clientmanagement.exception.BusinessException;
import com.aeoj.clientmanagement.mapper.ProblemRecordMapper;
import com.aeoj.clientmanagement.service.JudgeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aeoj.clientmanagement.domain.problem.Problem;
import com.aeoj.clientmanagement.service.ProblemService;
import com.aeoj.clientmanagement.mapper.ProblemMapper;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
* @author 20620
* @description 针对表【aeoj_problem(题目表)】的数据库操作Service实现
* @createDate 2025-04-24 19:41:19
*/
@Service
public class ProblemServiceImpl extends ServiceImpl<ProblemMapper, Problem>
    implements ProblemService{
    @Resource
    private ProblemRecordMapper problemRecordMapper;

    @Resource
    @Lazy
    private JudgeService judgeService;

    @Override
    public Long submit(ProblemSubmitDTO dto, SysUserVO loginUser) {
        String language = dto.getLanguage();
        ProblemSubmitLanguageEnum languageEnum = ProblemSubmitLanguageEnum.getByCode(language);
        if (languageEnum == null) {
            throw new BusinessException(ResponseCodeEnum.BAD_REQUEST);
        }

        Problem problem = this.getById(dto.getProblemId());
        if (problem == null) {
            throw new BusinessException(ResponseCodeEnum.BAD_REQUEST);
        }

        ProblemRecord problemRecord = new ProblemRecord();
        problemRecord.setProblemId(problem.getId());
        problemRecord.setUserId(loginUser.getUserId());
        problemRecord.setRoomId(dto.getRoomId());
        problemRecord.setStatus(ProblemRrecordStatusEnum.PENDING.getCode());
        problemRecord.setCode(dto.getCode());
        problemRecord.setLanguage(languageEnum.getCode());
        problemRecord.setCreateTime(new Date());

        int insert = problemRecordMapper.insert(problemRecord);
        if (insert != 1) {
            throw new BusinessException(ResponseCodeEnum.BUSINESS_ERROR);
        }

        Long problemRecordId = problemRecord.getId();
        CompletableFuture.runAsync(() -> {
            judgeService.doJudge(problemRecordId);
        });

        return problemRecordId;
    }
}




